package org.example.spi;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.serializer.Serializer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SpiLoader {
    //存储已加载的类：接口名 => (key => 实现类)
    private static Map<String, Map<String,Class<?>>> loaderMap = new ConcurrentHashMap<>();

    //对象实例缓存(避免重复new), 类路径 => 对象实例,单例模式
    private static Map<String,Object> instanceCache = new ConcurrentHashMap<>();

    //系统SPI目录
    private static final String RPC_SYSTEM_SPI_DIR = "META-INF/rpc/system/";

    //用户自定义SPI目录
    private static final String RPC_CUSTOM_SPI_DIR = "META-INF/rpc/custom/";

    //扫描路径
    private static final String[] SCAN_DIRS = new String[]{RPC_CUSTOM_SPI_DIR,RPC_SYSTEM_SPI_DIR};

    //动态加载的类列表,存放接口
    private static final List<Class<?>> LOAD_CLASS_LIST = Arrays.asList(Serializer.class);

    public static void loadAll(){
        log.info("加载所有SPI");
        for (Class<?> aClass : LOAD_CLASS_LIST) {
            load(aClass);
        }
    }

    /**
     * 获取某个接口的实例
     * @param tClass
     * @param key
     * @return
     * @param <T>
     */
    public static <T> T getInstance(Class<?> tClass, String key){
        System.out.println(Thread.currentThread().getName() + "执行SpiLoader中的getInstance(tClass,key)方法"
                            + "参数为：" + tClass.toString() + "|" + key);
        //获取接口的类名
        String tClassName = tClass.getName();
        //获取接口对应的实现类映射
        Map<String, Class<?>> keyClassMap = loaderMap.get(tClassName);
        //如果接口对应的实现类映射不存在，抛出异常
        if (keyClassMap == null){
            throw new RuntimeException(String.format("SpiLoader 未加载 %s 类型",tClassName));
        }
        //如果接口对应的实现类映射中不存在指定的key，抛出异常
        if (!keyClassMap.containsKey(key)){
            throw new RuntimeException(String.format("SpiLoader的%s 不存在 key=%s 的类型",tClassName,key));
        }
        //获取到要加载的实现类型
        Class<?> implClass = keyClassMap.get(key);
        //从实例缓存中加载指定类型的实例
        String implClassName = implClass.getName();
        //如果实例缓存中不存在指定类型的实例，则实例化并放入缓存
        if (!instanceCache.containsKey(implClassName)){
            try {
                instanceCache.put(implClassName,implClass.newInstance());
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(String.format("%s 类实例化失败",implClassName),e);
            }
        }
        //返回指定类型的实例
        return (T) instanceCache.get(implClassName);
    }

    /**
     * 加载某个类型
     * @param loadClass
     * @return
     */
    public static Map<String,Class<?>> load(Class<?> loadClass) {
        //打印当前线程名称和执行方法
        System.out.println(Thread.currentThread().getName() + "执行SpiLoader中的load(loadClass)方法"
                            + "参数为：" + loadClass.toString());

        //记录日志，加载类型为loadClass的SPI
        log.info("加载类型为 {} 的SPI",loadClass.getName());
        //扫描路径，用户自定义的SPI优先级高于系统SPI
        Map<String,Class<?>> keyClassMap = new HashMap<>();
        //遍历SCAN_DIRS中的路径
        for (String scanDir : SCAN_DIRS) {
            //获取资源文件
            List<URL> resources = ResourceUtil.getResources(scanDir + loadClass.getName());
            //读取每个资源文件
            for (URL resource : resources) {
                try {
                    InputStreamReader inputStreamReader = new InputStreamReader(resource.openStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    //逐行读取资源文件
                    while((line = bufferedReader.readLine()) != null) {
                        String[] strArray = line.split("=");
                        //如果行中有等号，则分割出key和className
                        if (strArray.length > 1){
                            String key = strArray[0];
                            String className = strArray[1];
                            //将key和className放入keyClassMap中
                            keyClassMap.put(key,Class.forName(className));
                        }
                    }
                } catch (Exception e) {
                    //记录错误日志
                    log.error("spi resource load error",e);
                }
            }
        }
        //将keyClassMap放入loaderMap中
        loaderMap.put(loadClass.getName(),keyClassMap);
        return keyClassMap;
    }
}
